//封装的是fetch
import querystring from "querystring";

//封装get方法
export function get(url, params = {}) {
  /* 
    当前params 传递的是{a:1,b:2}
    url:'/api/?a=1&b=2'
    */
  let newParms = querystring.stringify(params);
  //实例化promise
  return new Promise((resolve) => {
    let headers = {};
    if (url != "/api/login" && url != "/api/register") {
      headers = {
        authorization: JSON.parse(sessionStorage.getItem("isLogin")).token,
      };
    } else {
      headers = {};
    }

    //调用fetch
    fetch(`${url}?${newParms}`, {
      headers,
    })
      .then((res) => res.json())
      .then((res) => {
        resolve(res);
      });
  });
}

//封装post方法
export function post(url, params = {}, isFile = false) {
  //先设置请求头 如果必须要加token
  let headers = {};
  if (url != "/api/login" && url != "/api/register") {
    headers = {
      authorization: JSON.parse(sessionStorage.getItem("isLogin")).token,
    };
  } else {
    headers = {};
  }
  let data = null;
  if (isFile) {
    data = new FormData();
    for (let i in params) {
      data.append(i, params[i]);
    }
  } else {
    data = querystring.stringify(params);
    //需要重新设置请求头
    headers = {
        ...headers,
        "Content-Type": "application/x-www-form-urlencoded"
    }
  }
  return new Promise(resolve=>{
      fetch(url,{
        method: "post",
        body:data,
        headers
      })
      .then(res=>res.json())
      .then(res=>{
          resolve(res)
      })
  })
}
